package com.aipp.mall.h5.service;

import com.aipp.mall.common.exception.ServerException;
import com.aipp.mall.common.utils.SecurityUtil;
import com.aipp.mall.h5.domain.dto.OrderProductListDTO;
import com.aipp.mall.h5.domain.entity.OrderItem;
import com.aipp.mall.h5.mapper.OrderItemMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.hutool.core.data.id.IdUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单中所包含的商品Service业务层处理
 *
 * @author zcc
 */
@Service
public class OrderItemService extends ServiceImpl<OrderItemMapper, OrderItem> {

    @Transactional(rollbackFor = Exception.class)
    public void saveOrderItem(LocalDateTime optTime,
                              Long orderId, List<OrderProductListDTO> list) {
        List<OrderItem> addOrderItemList = new ArrayList<>();
        list.forEach(item -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setId(IdUtil.getSeataSnowflakeNextId());
            orderItem.setOrderId(orderId);
            orderItem.setProductId(item.getProduct().getId());
            orderItem.setOutProductId(item.getProduct().getOutProductId());
            orderItem.setSkuId(item.getSku().getId());
            orderItem.setOutSkuId(item.getSku().getOutSkuId());
            orderItem.setPic(item.getSku().getPic());
            orderItem.setProductName(item.getProduct().getName());
            orderItem.setSalePrice(item.getSku().getPrice());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setProductCategoryId(item.getProduct().getCategoryId());
            orderItem.setSpData(item.getSku().getSpData());
            orderItem.setCreateBy(SecurityUtil.getMemberId());
            orderItem.setCreateTime(optTime);
            addOrderItemList.add(orderItem);
        });
        boolean flag = saveBatch(addOrderItemList);
        if (!flag) {
            throw new ServerException("新增订单item失败");
        }
    }
}
